//
//  Services+Setup.swift
//  App
//
//  Created by chenyh on 2018/5/28.
//
//import FluentSQLite
import Vapor
import FluentMySQL
import Leaf
import Console


extension Services {
    
    public mutating func setup() throws {
        
        try setupSQLiteProvider()
        try setupRoutes()
        try setupMiddleware()
        try setupDBConfig()
        try setupPreparations()
        try setupEnvAddress()
        try setupLeatConfig()
       
        
    }
    private mutating func setupLoggingProvider() throws {

         self.register(PrintLogger())
    }
    private mutating func setupSQLiteProvider() throws {
        /// Register providers first
//        try self.register(FluentSQLiteProvider())
        try self.register(FluentMySQLProvider())
    }
    private mutating func setupRoutes() throws {
        /// Register routes to the router
        let router = EngineRouter.default()
        try routes(router)
        self.register(router, as: Router.self)
    }
    private mutating func setupMiddleware() throws {
        /// Register middleware
        var middlewares = MiddlewareConfig() // Create _empty_ middleware config
//            middlewares
            middlewares.use(FileMiddleware.self) // Serves files from `Public/` directory
            middlewares.use(ErrorMiddleware.self) // Catches errors and converts to HTTP response
        

        self.register(middlewares)
    }
    private mutating func setupDBConfig() throws {
      
//        var migrations = MigrationConfig()
        
        let mysqlConfig = MySQLDatabaseConfig(hostname: "localhost", port: 3306, username: "root", password: "123456", database: "vapor")
        self.register(mysqlConfig)
//        // Configure a SQLite database
//        let sqlite = try SQLiteDatabase(storage: .memory)
//
//        /// Register the configured SQLite database to the database config.
//        var databases = DatabasesConfig()
//            databases.add(database: sqlite, as: .sqlite)
//            self.register(databases)
        
 
    }
    private mutating func setupEnvAddress() throws {
        var nioConfig = NIOServerConfig.default()
            nioConfig.hostname = "0.0.0.0"
            nioConfig.port = 8888
        self.register(nioConfig)
        
    }
    private mutating func setupPreparations() throws {
        /// Configure migrations

        var migrations = MigrationConfig()
        //创建的模型
            migrations.add(model: Todo.self, database: .mysql)
            migrations.add(model: Account.self, database: .mysql)
        
        self.register(migrations)
    }
    private mutating func setupLeatConfig() throws {
       try self.register(LeafProvider())
    }
}
